/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.admin.addins;

import org.gidoo.cms.helper.Crypto;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.gidoo.cms.admin.AdminPage;
import org.gidoo.cms.login.GidooCMSSession;

/**
 * A panel where you can adminstrate all users.
 * Implemented stuff so on: <br>
 * - adding new user
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class UsersPanel extends AddInPanel
{

  private Form formNewUser;
  private TextField<String> txtNewUser;
  private TextField<String> txtRealName;
  private TextField<String> txtEMail;
  private PasswordTextField txtPassword1;
  private PasswordTextField txtPassword2;
  private CheckBox cbIsAdmin;
  private Button btNewUser;
  private AdminPage theParent;

  public UsersPanel(String id)
  {
    super(id);
  }
  
  /** Creates a new instance of UsersPanel */
  public UsersPanel(String id, AdminPage parent)
  {
    super(id);
    this.theParent = parent;

    formNewUser = new Form("formNewUser");
    add(formNewUser);

    txtNewUser = new TextField<String>("txtNewUser", new Model(""));
    txtRealName = new TextField<String>("txtRealName", new Model(""));
    txtEMail = new TextField<String>("txtEMail", new Model(""));
    txtPassword1 = new PasswordTextField("txtPassword1", new Model(""));
    txtPassword2 = new PasswordTextField("txtPassword2", new Model(""));
    cbIsAdmin = new CheckBox("cbIsAdmin", new Model(new Boolean(false)));
    btNewUser = new Button("btNewUser", new ResourceModel("addnewuser"))
    {
      @Override
      public void onSubmit()
      {
        addNewUser();
      }
    };

    txtNewUser.setRequired(true);
    txtNewUser.setLabel(new ResourceModel("newusername"));
    txtRealName.setRequired(true);
    txtRealName.setLabel(new ResourceModel("realname"));
    txtEMail.setRequired(true);
    txtEMail.add(EmailAddressValidator.getInstance());
    txtEMail.setLabel(new ResourceModel("emailaddress"));
    txtPassword1.setLabel(new ResourceModel("initialpassword"));
    txtPassword2.setLabel(new ResourceModel("retype"));

    formNewUser.add(txtNewUser);
    formNewUser.add(txtRealName);
    formNewUser.add(txtEMail);
    formNewUser.add(txtPassword1);
    formNewUser.add(txtPassword2);
    formNewUser.add(cbIsAdmin);
    formNewUser.add(btNewUser);
  }

  protected void addNewUser()
  {
    if(txtPassword1.getValue() != null && txtPassword1.getValue().equals(txtPassword2.getValue()))
    {
      try
      {
        GidooCMSSession session = (GidooCMSSession) getSession();
        Node users = session.getJcrRootNode().getNode("users");

        if(users.hasNode(txtNewUser.getModelObject()))
        {
          error(getString("userexists"));
          return;
        }

        Node newUser = users.addNode(txtNewUser.getModelObject());

        try
        {
          newUser.setProperty("passwordhash",
            Crypto.calculateSHAHash(txtPassword1.getModelObject()));
        }
        catch(Exception ex)
        {
          error(getString("cryptoerror"));
        }
        newUser.setProperty("email", txtEMail.getModelObject());
        newUser.setProperty("realname", txtRealName.getModelObject());
        newUser.setProperty("isadmin", ((Boolean) cbIsAdmin.getModelObject()).booleanValue());

        newUser.addNode("edit");
        newUser.addNode("publish");

        users.save();

        theParent.updateDataAndView();
        info(getString("usercreated"));

      }
      catch(RepositoryException ex)
      {
        Logger.getLogger(UsersPanel.class.getName()).log(Level.SEVERE, null, ex);
        error(getString("jcrerror"));
      }
    }
    else
    {
      error(getString("passwordsnotequal"));
    }
  }
}
